package com.testing.httpclient;


import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import com.testing.utils.ExcelWriter;
import com.testing.utils.LoggerConfig;
import com.testing.utils.LoginUtils;
import com.testing.utils.Utils;

import javax.naming.NamingEnumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpClientControl {

    private HttpClientKeyWord httpClientKeyWord;

    private ExcelWriter excelWriter;

    private String body;

    public int nowRow = 0;

    public HttpClientControl(ExcelWriter excelWriter) {
        httpClientKeyWord = new HttpClientKeyWord();
        this.excelWriter = excelWriter;
    }

    public HttpClientControl(){
        super();
        httpClientKeyWord = new HttpClientKeyWord();
    }

    // 开启保存Cookie
    public void saveCookie() {
        // 设置useCookie的状态为真
        httpClientKeyWord.saveCookie();
    }

    // 不加载Cookie
    public void clearCookie() {
        httpClientKeyWord.clearCookie();
    }

    // 清除header
    public void clearHeader() {
        httpClientKeyWord.clearHeader();
    }

    // 去除空格
    public String optimization(String text) {
        return Utils.optimization(text);
    }

    /**
     * 添加头部信息
     * @param text 传入json格式 {"status":200,"msg":"success","token":"bf1ba423cec6485fb9f2fc1ffcc29285"}
     */
    public void addHeaderPar(String text) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            String par = httpClientKeyWord.parReplace(optimization(text));
            LoggerConfig.LOGGER.info("解析后的参数:" + par);
            JSONObject jsonObject = JSONObject.parseObject(par);
            Set<String> set = jsonObject.keySet();
            for (String key : set) {
                map.put(key, String.valueOf(jsonObject.get(key)));
            }
            // 添加最终需要的参数以及键值对
            httpClientKeyWord.addHeader(map);
            if (excelWriter != null){
                excelWriter.writeCell(nowRow,11,"pass");
                excelWriter.writeCell(nowRow,12,body);
            }
        } catch (Exception e) {
            LoggerConfig.LOGGER.error("······解析json失败·····");
            LoggerConfig.LOGGER.error(e.fillInStackTrace());
            if (excelWriter != null){
                excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
                excelWriter.writeFailCell(nowRow,11,"Fail");
            }
        }
    }

    /**
     * 用于手动保存参数
     * @param text  传入json字符串
     */
    public void addParameterForJsonText(String text){
        JSONObject jsonObject = JSONObject.parseObject(text);
        Set<String> set = jsonObject.keySet();
        for (String key : set) {
            httpClientKeyWord.addParameter(key, httpClientKeyWord.parReplace(String.valueOf(jsonObject.get(key))));
        }
    }

    /**
     *  用于需要保存的数据
     * @param key 传入键
     * @param value 传入值
     */
    public void addParameterForText(String key,String value){
        httpClientKeyWord.addParameter(key,httpClientKeyWord.parReplace(value));
    }

    /**
     * @param key      传入需要保存的key,jsonPaths
     * @param jsonPath 传入获取key对应值的jsonPath,多个逗号分隔
     */
    public void saveParameter(String key, String jsonPath) {
        // 当需要保存多个参数时
        if (key.contains(",") && jsonPath.contains(",")) {
            try {
                String[] keys = optimization(key).split(",");
                String[] jsonPaths = optimization(key).split(",");
                for (int i = 0; i < keys.length; i++) {
                    String key_value = JsonPath.read(body, jsonPaths[i]).toString();
                    // 调用addParameter保存参数
                    httpClientKeyWord.addParameter(keys[i], key_value);
                }
                if (excelWriter != null){
                    excelWriter.writeFailCell(nowRow,11,"PASS");
                    excelWriter.writeCell(nowRow,12,body);
                }
            } catch (Exception e) {
                LoggerConfig.LOGGER.error(e.fillInStackTrace().toString());
                e.printStackTrace();
                if (excelWriter != null){
                    excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
                    excelWriter.writeFailCell(nowRow,11,"Fail");
                }
            }
        } else {
            try {
                // 当只需要保存单个参数时
                String key_value = JsonPath.read(body, jsonPath);
                // 调用addParameter保存参数
                httpClientKeyWord.addParameter(key, key_value);
                if (excelWriter != null){
                    excelWriter.writeCell(nowRow,12,body);
                }
            } catch (Exception e) {
                LoggerConfig.LOGGER.error(e.fillInStackTrace().toString());
                e.printStackTrace();
                if (excelWriter != null){
                    excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
                    excelWriter.writeFailCell(nowRow,11,"Fail");
                }
            }
        }
    }

    /**
     * @param url 请求连接地址
     * @param par 请求参数,例如id={id}&name={name}
     */
   public String doGet(String url, String par){
       try {
           if (optimization(par).length() > 0){
               // 替换掉里面的参数
               par = httpClientKeyWord.parReplace(optimization(par));
           }
           body = httpClientKeyWord.doGet(url,par);
           if (excelWriter != null){
               excelWriter.writeCell(nowRow,12,body);
           }
       } catch (Exception e) {
           LoggerConfig.LOGGER.error(e.fillInStackTrace().toString());
           e.printStackTrace();
           if (excelWriter != null){
               excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
               excelWriter.writeFailCell(nowRow,11,"Fail");
           }
       }
       return body;
   }

    /**
     * @param url 传入请求地址
     * @param param 传入参数，格式为json格式 {"status":200,"msg":"success","token":"bf1ba423cec6485fb9f2fc1ffcc29285"}
     */
   public String doPostForm(String url , String param){
       Map<String,String> map = new HashMap<String, String>();
       try {
           param = httpClientKeyWord.parReplace(optimization(param));
           if (param.length() > 0 ){
               JSONObject jsonObject = JSONObject.parseObject(param);
               Set<String> set = jsonObject.keySet();
               for (String key : set) {
                   map.put(key, String.valueOf(jsonObject.get(key)));
               }
           }
           body = httpClientKeyWord.doPostForm(url,map);
           if (excelWriter != null){
               excelWriter.writeCell(nowRow,12,body);
           }
       } catch (Exception e) {
           LoggerConfig.LOGGER.error(e.fillInStackTrace().toString());
           e.printStackTrace();
           if (excelWriter != null){
               excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
               excelWriter.writeFailCell(nowRow,11,"Fail");
           }
       }
       return body;
   }

    /**
     * @param url 传入请求地址
     * @param param 传入参数，格式为json格式 {"status":200,"msg":"success","token":"bf1ba423cec6485fb9f2fc1ffcc29285"}
     */
    public String doPostJson(String url , String param){
        try {
            param = httpClientKeyWord.parReplace(optimization(param));
            body = httpClientKeyWord.doPostJson(url,param);
            if (excelWriter != null){
                excelWriter.writeCell(nowRow,12,body);
            }
        } catch (Exception e) {
            LoggerConfig.LOGGER.error(e.fillInStackTrace().toString());
            e.printStackTrace();
            if (excelWriter != null){
                excelWriter.writeCell(nowRow,12,e.fillInStackTrace().toString());
                excelWriter.writeFailCell(nowRow,11,"Fail");
            }
        }
        return body;
    }

    // 获取jsonPath对应的值
    public String getJsonPathValue(String jsonPath){
        return  JsonPath.read(body, jsonPath).toString();
    }

    // 传入实际结果与预期结果比较
    public boolean equal(String actual,String exp){
        String actualStr = JsonPath.read(body, actual).toString();
        // 实际结果与预期结果比较
        if (actualStr.equals(exp)){
            if (excelWriter != null){
                excelWriter.writeCell(nowRow,11,"Pass");
            }
            return true;
        }else {
            if (excelWriter != null){
                excelWriter.writeFailCell(nowRow,11,"Fail");
            }
            return false;
        }
    }

    /**
     * 手动添加指定的信息到保存参数的map中
     * @param keys 键
     * @param text 值，json格式
     */
    public void getLoginEncryption(String keys,String text){
        Map<String,String> map = new HashMap<>();
        if (text.length() > 0){
            JSONObject jsonObject = JSONObject.parseObject(text);
            Set<String> set = jsonObject.keySet();
            for (String key : set) {
                map.put(key, httpClientKeyWord.parReplace(String.valueOf(jsonObject.get(key))));
            }
        }
        if (map.size() > 0){
            LoginUtils loginUtils = new LoginUtils();
            String loginEncryptionText = loginUtils.getSignatureStr(map);
            LoggerConfig.LOGGER.info(loginEncryptionText);
            addParameterForText(keys,loginEncryptionText);
            excelWriter.writeCell(nowRow,11,"Pass");
        }
    }

    // 保存当前时间搓
    public void getData(String key){
        LoggerConfig.LOGGER.info("getData:" + key);
        addParameterForText(key,String.valueOf(Utils.getDateTime()));
        excelWriter.writeCell(nowRow,11,"Pass");
    }

    // body 包含指定内容
    public boolean contains(String exp){
        if (body.contains(exp)){
            excelWriter.writeCell(nowRow,11,"Pass");
            return true;
        }else {
            excelWriter.writeCell(nowRow,11,"Fail");
            return false;
        }
    }
}
